<?php


namespace app\api\service;


use app\api\model\User;
use app\api\model\UserAuth;
use app\api\model\UserAuthImg;

class CreateUserAuth extends Token
{
    // 提交信息
    private $putArr;

    // 用户信息
    private $user;

    public function __construct($putArr)
    {
        $this->putArr = $putArr;
        $this->user = User::where('id',self::getCurrentUid())->find();
    }

    // 入口方法
    public function entrance()
    {
        /**
         * 1. 判断信息
         * 2. 添加信息
         */
        return $this->judgeData();
    }

    // 判断信息
    private function judgeData()
    {
        $info = UserAuth::where('openid',$this->user['openid'])->find();
        $img_data = [];
        if($info) {
            $this->putArr['status'] = 1;
            $this->putArr['state'] = 1;
            $this->putArr['status_con'] = '';
            foreach ($this->putArr['fileList'] as $k=>$v){
                $img_data[$k] = [ 'img_id'=>$v['img_id'] , 'user_auth_id' => $info['id']];
            }
            unset($this->putArr['fileList']);
            unset($this->putArr['region']);
            UserAuth::where('id',$info['id'])->update($this->putArr);
            UserAuthImg::destroy(['user_auth_id' => $info['id']]);
            $imgs = new UserAuthImg();
            $imgs->allowField(true)->saveAll($img_data);
            return writeJson(201, [], '修改成功,已提交后台审核！');
        } else {
            $this->putArr['status'] = 1;
            $this->putArr['state'] = 1;
            $this->putArr['openid'] = $this->user['openid'];
            $mode = UserAuth::create($this->putArr);
            foreach ($this->putArr['fileList'] as $k=>$v){
                $img_data[$k] = ['img_id'=>$v['img_id']];
            }
            $mode->imgs()->saveAll($img_data);
            return writeJson(201, [], '添加成功,已提交后台审核！');
        }
    }
}